
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[EBAS_SP_HENT_KARAKTER]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[EBAS_SP_HENT_KARAKTER]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [DBO].[EBAS_SP_HENT_KARAKTER] 
	@session varchar(255),
	@karakter varchar(255) = NULL,
	@karakterSkala varchar(255) = NULL
WITH ENCRYPTION
AS
	DECLARE @rettighed int,
		@guid uniqueidentifier,
		@karakterSkalaGuid uniqueidentifier,
		@antal int
	
	SET NOCOUNT ON

	CREATE TABLE #temp ( rett int )
	INSERT INTO #temp (rett)
	EXEC EBAS.DBO.EBAS_SP_SIKKERHED_VERIFICER_SESSION @session	

	SET @rettighed = (SELECT IsNull(MAX(rett),0) FROM #temp)
	
	IF 8 <= @rettighed 
	BEGIN
		SET @karakterSkalaGuid = ( SELECT GUID FROM EBAS_KARAKTER_SKALA
				 	   WHERE NAVN = @karakterSkala )
					
		IF @karakter IS NULL AND @karakterSkala IS NULL
			SELECT 	K.GUID, K.KARAKTER, K.KARAKTER_SKALA_GUID, KS.NAVN AS KARAKTER_SKALA, 
				1 AS ANTAL
			FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
			WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
		ELSE IF @karakter IS NOT NULL AND @karakterSkala IS NULL
		BEGIN
			SET @antal = ( 	SELECT 	COUNT(*)
					FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
					WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
					AND	K.KARAKTER = @karakter )		
		
			SELECT 	K.GUID, K.KARAKTER, K.KARAKTER_SKALA_GUID, KS.NAVN AS KARAKTER_SKALA, 
				1 AS ANTAL
			FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
			WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
			AND	K.KARAKTER = @karakter
		END
		ELSE IF @karakter IS NULL AND @karakterSkala IS NOT NULL
		BEGIN
			SET @antal = ( 	SELECT 	COUNT(*)
					FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
					WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
					AND	KS.GUID = @karakterSkalaGuid )
		
			SELECT 	K.GUID, K.KARAKTER, K.KARAKTER_SKALA_GUID, KS.NAVN AS KARAKTER_SKALA, 
				@antal AS ANTAL
			FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
			WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
			AND	KS.GUID = @karakterSkalaGuid
		END
		ELSE IF @karakter IS NOT NULL AND @karakterSkala IS NOT NULL
			SELECT 	K.GUID, K.KARAKTER, K.KARAKTER_SKALA_GUID, KS.NAVN AS KARAKTER_SKALA, 
				1 AS ANTAL
			FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
			WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
			AND	K.KARAKTER = @karakter
			AND	KS.GUID = @karakterSkalaGuid
	END
	ELSE
		SELECT 	K.GUID, K.KARAKTER, K.KARAKTER_SKALA_GUID, KS.NAVN AS KARAKTER_SKALA, 
			0 AS ANTAL
		FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
		WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
		AND 	K.GUID IS NULL
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
